package parser

import (
	"learngo/crawler/engine"
	"learngo/crawler/model"
	"regexp"
	"strconv"
	"strings"
)

var (
	purpleAllReg = regexp.MustCompile(`<div class="m-btn purple" [^>]+>([^<]+)</div>`)
	ageReg       = regexp.MustCompile(`<div class="m-btn [^\"]+" [^>]+>([^<]+)岁</div>`)
	xingzuoReg   = regexp.MustCompile(`<div class="m-btn [^\"]+" [^>]+>([^<]+座)[^<]+</div>`)
	heightReg    = regexp.MustCompile(`<div class="m-btn [^\"]+" [^>]+>([^<]+)cm</div>`)
	weightReg    = regexp.MustCompile(`<div class="m-btn [^\"]+" [^>]+>([^<]+)kg</div>`)
	incomeReg    = regexp.MustCompile(`<div class="m-btn [^\"]+" [^>]+>月收入:([^<]+)</div>`)
	hukouReg     = regexp.MustCompile(`<div class="m-btn [^\"]+" [^>]+>籍贯:([^<]+)</div>`)
	houseReg     = regexp.MustCompile(`<div class="m-btn pink" [^>]+>([^<]*住[^<]*|[^<]*房[^<]*)</div>`)
	carReg       = regexp.MustCompile(`<div class="m-btn [^\"]+" [^>]+>(已买车|未买车)</div>`)
	idUrlReg     = regexp.MustCompile(`http://album.zhenai.com/u/([\d]+)`)
)

func ParseProfile(contents []byte, url, name, gender string) engine.ParseResult {
	profile := model.Profile{Name: name, Gender: gender}

	purpleAllMatch := purpleAllReg.FindAllSubmatch(contents, -1)
	if len(purpleAllMatch) > 0 {
		profile.Marriage = string(purpleAllMatch[0][1])
		profile.Occupation = string(purpleAllMatch[len(purpleAllMatch)-2][1])
		if strings.Contains(profile.Occupation, "月收入") {
			profile.Occupation = ""
		}
		profile.Education = string(purpleAllMatch[len(purpleAllMatch)-1][1])
	}

	if age, err := strconv.Atoi(extractString(contents, ageReg)); err == nil {
		profile.Age = age
	}

	if height, err := strconv.Atoi(extractString(contents, heightReg)); err == nil {
		profile.Height = height
	}

	if weight, err := strconv.Atoi(extractString(contents, weightReg)); err == nil {
		profile.Weight = weight
	}

	profile.Xingzuo = extractString(contents, xingzuoReg)
	profile.Income = extractString(contents, incomeReg)
	profile.Hukou = extractString(contents, hukouReg)
	profile.House = extractString(contents, houseReg)
	profile.Car = extractString(contents, carReg)

	rs := engine.ParseResult{
		Items: []engine.Item{
			{
				Id:      extractString([]byte(url), idUrlReg),
				Url:     url,
				Type:    "zhenai",
				Payload: profile,
			},
		},
	}

	return rs
}

func extractString(contents []byte, re *regexp.Regexp) string {
	match := re.FindSubmatch(contents)
	if len(match) >= 2 {
		return string(match[1])
	}

	return ""
}
